/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * This file is part of retabel.
 *
 * Copyright (c) 2011 by individual contributors as indicated by the
 * @author tags. See the copyright.txt file in the distribution
 * for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.retabel.web.rest;

import org.retabel.persistence.entity.document.SectionConfiguration;
import org.retabel.service.manager.SectionConfigurationManager;
import org.retabel.service.mapper.XmlSectionConfigurationMapper;
import xsd.sectionconfigurations.ObjectFactory;
import xsd.sectionconfigurations.SectionConfigurationList;
import xsd.sectionconfigurations.SectionConfigurations;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBElement;

/**
 * Section configuration REST interface implementation
 * <p/>
 * <h3>Extra-Info</h3>
 * Created: 10:19 16.07.11
 *
 * @author Peter Herber
 * @version 1.0
 */
@Path("/config/sections/")
@Stateless
public class SectionConfigurationServiceBean extends RestServiceBean {

    // constants

    @EJB
    private SectionConfigurationManager sectionConfigurationManager;

    @EJB
    private XmlSectionConfigurationMapper xmlSectionConfigurationMapper;

    @GET
    @Produces(MediaType.TEXT_XML)
    public Response getSectionConfigurations(@QueryParam("first") Integer first,
                                                                       @QueryParam("maxRows") Integer maxRows) {
        int maxRowsWithFallback = maxRows != null ? maxRows : getDefaultMaxResultsPerPage();
        int firstWithFallback = first != null ? first : 0;

        int count = sectionConfigurationManager.count();
        SectionConfiguration[] sectionConfigurations = sectionConfigurationManager.findAllSorted(firstWithFallback,
                                                                                                 maxRowsWithFallback);
        ObjectFactory of = new ObjectFactory();

        SectionConfigurations result = of.createSectionConfigurations();
        result.setStart(firstWithFallback);
        result.setRows(sectionConfigurations.length);
        result.setCount(count);

        SectionConfigurationList sectionConfigurationList = of.createSectionConfigurationList();
        result.setList(sectionConfigurationList);

        for (SectionConfiguration sectionConfiguration : sectionConfigurations) {
            xsd.sectionconfigurations.SectionConfiguration resultSectionConfiguration = of.createSectionConfiguration();
            resultSectionConfiguration.setName(sectionConfiguration.getName());
            resultSectionConfiguration.setVersion(sectionConfiguration.getVersion());
            resultSectionConfiguration.setId(sectionConfiguration.getId());

            sectionConfigurationList.getSectionConfiguration().add(resultSectionConfiguration);
        }

        return Response.ok(result).build();
    }

    @POST
    @Consumes(MediaType.APPLICATION_XML)
    @Produces(MediaType.TEXT_PLAIN)
    public Response postSectionConfiguration(byte[] bytes, @Context UriInfo uriInfo) {
        PlainTextResponseBuilder response = new PlainTextResponseBuilder(uriInfo);

        response.println("Attempting to store section configuration ...");


        try {
            response.println("xmlData: [" + bytes.length + "]");
            sectionConfigurationManager.store(bytes);
        } catch (Exception e) {
            response.println(e.toString());

            return response.getServerErrorResponse();
        }

        return response.getResponse();
    }

    @GET
    @Path("/{id}")
    @Produces(MediaType.TEXT_XML)
    public Response getSectionConfiguration(@PathParam("id") Integer id) {
        SectionConfiguration sectionConfiguration = sectionConfigurationManager.find(id);

        if (sectionConfiguration == null) {
            return Response.status(Response.Status.NOT_FOUND).build();
        }

        return Response.ok(xmlSectionConfigurationMapper.marshal(sectionConfiguration).getValue()).build();
    }

    @DELETE
    @Path("/{id}")
    @Produces(MediaType.TEXT_PLAIN)
    public Response deleteSectionConfiguration(@PathParam("id") Integer id, @Context UriInfo uriInfo) {
        PlainTextResponseBuilder response = new PlainTextResponseBuilder(uriInfo);

        response.println("Deleting section configuration: " + id);

        sectionConfigurationManager.remove(id);

        return response.getResponse();
    }

}
